package com.zx.mes.hyl.producer;

import com.zx.mes.hyl.entity.Order;
import com.zx.mes.hyl.service.OrderService;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

/**
 * order 订单 TransactionListener 实现
 *
 * @author 华云龙
 * @date 2018-12-10
 */
@Log4j2
@Data
public class TransactionListenerImpl implements TransactionListener {

    private OrderService orderService;

    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        log.debug("执行本地事务单元!msg:[" + new String( msg.getBody()) + "],arg:[" + arg + "]");
        try {
            Order order = (Order) arg;
            orderService.save(order);
        } catch (Exception e) {
            e.printStackTrace();
            /// 异常直接消息回滚
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
        return LocalTransactionState.COMMIT_MESSAGE;
    }

    /**
     * 当消息已经发送成功,但返回确认时网络波动,导致没有成功,可以在此做一步检测
     *
     * @param msg 消息体
     * @return 返回本地事务状态
     */
    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt msg) {
        log.info("回检:" + msg);
        return null;
    }
}
